package cn.edu.huas.shopping.pojo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Cart {
    private double account;
    private List<CartItem> items;


    /**
     * 向购物车中添加商品
     * @param pro
     * @param qty
     */
    public void  addItem(Product pro,int qty){
        //判断商品是否已经在集合当中(CartItem中提供了equals方法
        CartItem cartItem=new CartItem(pro,qty);
        if (items.contains(cartItem)){
            //找到商品，进行替换
            items.forEach(item->{
                if (item.getProduct().getId()== pro.getId()){
                    item.setQty(item.getQty()+qty);
                }
            });
        }else {
            items.add(cartItem);
        }
    }

    /**
     * 根据商品编号来移除商品条目
     * @param id
     * @return
     */
    public void deleteItem(Integer id){
        //根据传过来的id找到商品
        //CartItem cartItem=new CartItem();
        Iterator<CartItem> iterator = items.iterator();
        while (iterator.hasNext()){
            CartItem next = iterator.next();
            if (next.getProduct().getId()==id){
                iterator.remove();
            }
        }
    }
    /**
     * 获得购物车的总金额
     * @return
     */
    public double sunAccount(){
        double sun=0;
        for(CartItem item:items){
            sun+=item.getProduct().getShopPrice()*item.getQty();
        }
        return sun;
    }
    /**
     * 根新购物车中的商品数量
     * @param  id
     * @param qty
     */
    public void updataItem(Integer id,Integer qty){
        Iterator<CartItem> iterator = items.iterator();
        while (iterator.hasNext()){
            CartItem next = iterator.next();
            if (next.getProduct().getId()==id){
                next.setQty(qty);
            }
        }
    }

    /**
     * 清空购物车
     */
    public void clear(){

    }
    public Cart() {
        items=new ArrayList<>();
    }

    public Cart(double account, List<CartItem> items) {
        this.account = account;
        this.items = items;
    }

    public double getAccount() {
        double account=0;
        for(CartItem item:items){
            account+=item.getProduct().getShopPrice()*item.getQty();
        }
        return account;
    }

    public void setAccount(double account) {
        this.account = account;
    }

    public List<CartItem> getItems() {
        return items;
    }

    public void setItems(List<CartItem> items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return "Cart{" +
                "account=" + account +
                ", items=" + items +
                '}';
    }
}
